function varargout = TLConstantDlg(action,varargin)

% TL_CONSTANT_DLG manages the user interface for TargetLink Constant block
%
% SYNTAX dlgInfo = TLConstantDlg('GetDlgInfo');
%   gets dialog info of TargetLink Constant block
%
%   INPUT ARGUMENTS
%   -/-      
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = TLConstantDlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = TLConstantDlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = TLConstantDlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = TLConstantDlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX TLConstantDlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit, T. Pietzsch
% $RCSfile: TLConstantDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_SimBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.21 $
% $Date: 2011/07/21 13:08:16MESZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


switch action

    case 'GetDlgInfo'
        hBlock = varargin{1};
        dlgInfo = tl_get_dlginfodefaults('tlsim');
        titleName = 'Constant';
        pathinfo = tl_pathinfo(hBlock);
        dlgInfo.title = sprintf('TargetLink %s: %s', titleName, pathinfo.shortDisplayName);
        dlgInfo.bPlotSignal = 0;
        dlgInfo.pageNames   = {
            'Output'; ...
            'Autoscaling'; ...
            'Documentation'};
        varargout{1} = dlgInfo;
        varargout{2} = get_tlcg_data(hBlock);

    case 'CtrlPositions'
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        sheetDims    = varargin{4};
        switch pageName
            case 'Output'
                [sheetDims, ctrlPos] = ...
                    FcnCalcOutputCtrlPositions(commonGeom);

            case 'Autoscaling'
                excludedCtrls = {'logging', 'keepParameter'};
                [sheetDims, ctrlPos] = ...
                    TLManageLoggingCtrls('calcCtrls', commonGeom, sheetDims, excludedCtrls);

            case 'Documentation'
                bTblBlock = 0;
                bCodeComment = 1;
                [sheetDims, ctrlPos] = TLManageDocCtrls( ...
                    'ctrlpos', commonGeom, sheetDims, bCodeComment, bTblBlock);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;

    case 'Create'
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = strmatch(pageName, dlgdata.pageNames, 'exact');
        switch pageName
            case 'Output'
                dlgdata = FcnCreateOutputControls(pageNum, dlgfig, dlgdata);

            case 'Autoscaling'
                dlgdata = ...
                    TLManageLoggingCtrls('create', pageNum, dlgfig, dlgdata);

            case 'Documentation'
                dlgdata =  TLManageDocCtrls('create', pageNum, dlgfig, dlgdata);
        end
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;

    case 'Manage',
        pageName   = varargin{1};
        dlgfig     = varargin{2};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = strmatch(pageName, dlgdata.pageNames, 'exact');
        switch pageName
            case 'Output'
                [dlgdata, bModified] = ...
                    FcnManageOutputControls(pageNum, dlgfig, dlgdata, pageAction);

            case 'Autoscaling'
                [dlgdata, bModified] = ...
                    TLManageLoggingCtrls('manage', pageNum, dlgdata, pageAction, 'logdata');

            case 'Documentation'
                [dlgdata,bModified] = ...
                    TLManageDocCtrls('callback',pageNum,dlgfig,dlgdata,pageAction);
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified ;

    case 'ManageSystemIcons',
        dlgfig     = varargin{1};
        dlgdata    = varargin{2};
        pageAction = varargin{3};
        [dlgdata, bModified] = FcnManageSystemIcons(dlgfig,dlgdata,pageAction);
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'Update'
        dlgfig    = varargin{1};
        dlgdata   = varargin{2};
        pageNum   = varargin{3};

        pageName  = dlgdata.pageNames{pageNum};

        switch pageName
            case 'Output'
                dlgdata = FcnUpdateOutputControls(dlgdata, dlgfig, pageNum); % output page

            case 'Autoscaling'
                dlgdata.extdata.output.bIsInherit = strcmp(dlgdata.data.output.class, 'default');
                dlgdata =  TLManageLoggingCtrls('update',pageNum,dlgdata,'logdata','output');
                TLManageLoggingCtrls('setCtrls',pageNum, dlgfig, dlgdata);

            case 'Documentation'
                TLManageDocCtrls('update', pageNum, dlgfig, dlgdata);
        end
        varargout{1} = dlgdata;

    case 'Apply'
        dlgdata  = varargin{2};
        bClose   = varargin{3};
        [dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);
        varargout{1} = dlgdata;
        varargout{2} = bClose;

    otherwise
        error(['Invalid action "' action '"']);
end


%-----------------------------------------------------------------------------------------
% FcnManageSystemIcons manage actions of toolbar icons
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   action      action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageSystemIcons(dlgfig, dlgdata, action) %#ok

bModified = false;
switch action
    case 'EditCode'
        % look for associated production code file
        [codefile,blockstr] = get_codefile(dlgdata.model);
        if ~isempty(codefile)
            codeedit(codefile,blockstr);
        end

    case 'ViewCode'
        tl_create_links_to_model('ShowComputation',dlgdata.model, 'output');

    otherwise
        error('Invalid callback');

end % switch(action)


%-----------------------------------------------------------------------------------------
% FcnCalcOutputCtrlPositions calculates positions for all controls on output page
%
% INPUT ARGUMENTS
%   commonGeom      common geometrie information
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnCalcOutputCtrlPositions(commonGeom)

excludedCtrls = { 'saturate', 'inheritproperties' };
[sheetDims, ctrlPos, col, colDelta, rowDelta] = ...
    tl_calc_ctrls_positions(commonGeom, excludedCtrls);

strings_and_styles = { ...
    'Constant:',      'text'; ...
    'Tolerance',      'text'; ...
    '  %',            'text'; ...
    'Sample time',    'text'; ...
    'Use value of Data Dictionary variable',    'checkbox'};

[valLabelSize, ...
    toleranceLabelSize, ...
    toleranceunitLabelSize, ...
    sampleTimeLabelSize, ...
    useDDValueCheckboxSize] = ...
    ds_get_uicontrol_sizes(commonGeom, strings_and_styles);

% define new height for addoptGroupbox
ctrlPos.addoptGroupbox(4) = commonGeom.editHeight ...
    + commonGeom.checkboxHeight ...
    + rowDelta ...
    + commonGeom.frameBottomEdgeBuffer ...
    + commonGeom.frameTopEdgeBuffer;

%---------------------------------------
% 2nd row
cy = commonGeom.frameBottomEdgeBuffer;

% ddv checkbox
cx = col(2);
ctrlPos.useDDValueCheckbox = [cx, cy, useDDValueCheckboxSize];

%---------------------------------------
% 1st row
cy = cy + commonGeom.checkboxHeight + rowDelta;

% constant value label
cx = col(1);
ctrlPos.valLabel = [cx cy valLabelSize];

% constant value edit field
cx = col(2);
ctrlPos.valEdit = [cx cy ctrlPos.varEdit(3:4)];

% tolerance label
cx = col(6) - colDelta/3 - toleranceLabelSize(1);
ctrlPos.toleranceLabel = [cx cy toleranceLabelSize];

% tolerance edit
cx = col(6);
ctrlPos.toleranceEdit = [cx cy ctrlPos.widthEdit(3:4)];

% tolerance unit
cx = cx + ctrlPos.toleranceEdit(3);
ctrlPos.toleranceUnitLabel = [cx cy toleranceunitLabelSize];

% sample time label
cx = col(8) - colDelta/3 - sampleTimeLabelSize(1);
ctrlPos.sampleTimeLabel = [cx cy sampleTimeLabelSize];

% sample time edit
cx = col(8);
ctrlPos.sampleTimeEdit = [cx cy ctrlPos.unitEdit(3:4)];

% increase sheet dimensions
sheetDims(2) = sheetDims(2) ...
    + ctrlPos.addoptGroupbox(4) ...
    + commonGeom.textHeight;


%-----------------------------------------------------------------------------------------
% FcnCreateOutputControls creates the figure window
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateOutputControls(pageNum,dlgfig,dlgdata)

% create constant controls
ctrlPos = dlgdata.pageData{pageNum}.ctrlPos;
Children = dlgdata.pageData{pageNum}.children;
pageName = dlgdata.pageNames{pageNum};
% constant value and tolerance controls
Children.addoptGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Constant'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.addoptGroupbox);

Children.valLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'text', ...
    'String',             'Constant:', ...
    'Position',           ctrlPos.valLabel);

Children.valEdit = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.valEdit, ...
    'Callback',          sprintf('tldlg(''%s'',gcbf,''valEdit'')',pageName));

Children.toleranceLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'text', ...
    'String',             'Tolerance:', ...
    'Position',           ctrlPos.toleranceLabel);

Children.toleranceEdit = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.toleranceEdit, ...
    'Callback',          sprintf('tldlg(''%s'',gcbf,''toleranceEdit'')',pageName));

Children.toleranceUnitLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'text', ...
    'String',             ' %', ...
    'Position',           ctrlPos.toleranceUnitLabel);

Children.sampleTimeLabel = uicontrol( ...
    'Parent',            Children.addoptGroupbox, ...
    'Style',             'text', ...
    'String',            'Sample time:', ...
    'Position',          ctrlPos.sampleTimeLabel);

Children.sampleTimeEdit = uicontrol( ...
    'Parent',            Children.addoptGroupbox, ...
    'BackGroundColor',   'w', ...
    'Style',             'edit', ...
    'Position',          ctrlPos.sampleTimeEdit, ...
    'Callback',          sprintf('tldlg(''%s'',gcbf,''sampleTimeEdit'')',pageName));

Children.useDDValueCheckbox = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Use value of Data Dictionary variable', ...
    'Position',           ctrlPos.useDDValueCheckbox, ...
    'Callback',          sprintf('tldlg(''%s'',gcbf,''useDDValueCheckbox'')',pageName));

dlgdata.pageData{pageNum}.children = Children;

% create standard controls
dlgdata = TLManageVariableCtrls('create', pageNum, dlgfig, dlgdata);
dlgdata = TLManageScalingCtrls('create', pageNum, dlgfig, dlgdata);


%-----------------------------------------------------------------------------------------
% FcnManageOutputControls manages control actions of output page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageOutputControls(pageNum, dlgfig, dlgdata, pageAction)

Children  = dlgdata.pageData{pageNum}.children;

switch pageAction
    case 'valEdit'
        constantstr = tl_deblank(get(Children.valEdit, 'String'), 2);
        if ~isempty(constantstr)
            if strcmp(constantstr, 'ddv')
                if isempty(dlgdata.data.output.variable)
                    beep;
                else
                    dlgdata.data.output.value = ['ddv(''', dlgdata.data.output.variable, ''')'];
                    dlgdata.data.output.useddvariablevalue = true;
                end
            else
                dlgdata.data.output.value = constantstr;
            end
        else
            beep;
        end
        bModified = true;

    case 'toleranceEdit'
        tolerance = str2double(get(Children.toleranceEdit, 'String'));
        if ~isnan(tolerance) && numel(tolerance) && tolerance >= 0
            dlgdata.data.output.tolerance = real(tolerance);
        else
            beep;
        end
        bModified = true;

    case 'sampleTimeEdit'
        sampleTimeStr = tl_deblank(get(Children.sampleTimeEdit, 'String'),2);
        if ~isempty(sampleTimeStr)
            dlgdata.data.dt = sampleTimeStr;
        else
            beep;
        end
        bModified = true;
        
    case 'useDDValueCheckbox'
        if get(Children.useDDValueCheckbox, 'Value')
            dlgdata.data.output.value = ['ddv(''', dlgdata.data.output.variable, ''')'];
            dlgdata.data.output.useddvariablevalue = true;
        else
            dlgdata.data.output.useddvariablevalue = false;
        end
        bModified = true;

    otherwise
        [dlgdata, bModified1] = ...
            TLManageVariableCtrls('manage', pageNum, dlgfig, dlgdata, pageAction, 'output');
        [dlgdata, bModified2] = ...
            TLManageScalingCtrls('manage', pageNum, dlgfig, dlgdata, pageAction, 'output');
        bModified = bModified1 || bModified2;
end


%--------------------------------------------------------------------------
% FcnUpdateOutputControls updates the controls of the output tab
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateOutputControls(dlgdata, dlgfig, pageNum)

Children = dlgdata.pageData{pageNum}.children;

% default control status
valEditCtrlStatus            = struct('enable', 'on');
toleranceEditCtrlStatus      = struct('enable', 'on');
toleranceUnitLabelCtrlStatus = struct('enable', 'on');
sampleTimeEditCtrlStatus     = struct('enable', 'on');
useDDValueCheckboxCtrlStatus = struct('enable', 'on', 'value', 0);

% invoke standard update methods
dlgdata = TLManageVariableCtrls('update', pageNum, dlgdata, 'output');
[constantValue, constraint, bCompliant] = tl_get_param_constraints(dlgdata.data.output, dlgdata.extdata.output);
dlgdata = TLManageScalingCtrls('update', pageNum, dlgdata, 'output', constraint);

% status of ddv checkbox
useDDValueCheckboxCtrlStatus.enable = flag2str(~isempty(dlgdata.data.output.variable));
useDDValueCheckboxCtrlStatus.value = dlgdata.data.output.useddvariablevalue;

% update value field
valEditCtrlStatus.string = dlgdata.data.output.value;
if dlgdata.data.output.useddvariablevalue
    valEditCtrlStatus.enable = 'inactive';
end
valEditCtrlStatus.iserror = ~bCompliant;

toleranceEditCtrlStatus.string = dlgdata.data.output.tolerance;
sampleTimeEditCtrlStatus.string = dlgdata.data.dt;

simulatedLabelCtrlStatus        = tl_get_control_userdata(Children.simulatedLabel);
upperSimulatedValueCtrlStatus   = tl_get_control_userdata(Children.upperSimulatedValue);
lowerSimulatedValueCtrlStatus   = tl_get_control_userdata(Children.lowerSimulatedValue);
upperImplementedValueCtrlStatus = tl_get_control_userdata(Children.upperImplementedValue);
lowerImplementedValueCtrlStatus = tl_get_control_userdata(Children.lowerImplementedValue);
upperCalculatedValueCtrlStatus  = tl_get_control_userdata(Children.upperCalculatedValue);
lowerCalculatedValueCtrlStatus  = tl_get_control_userdata(Children.lowerCalculatedValue);

if dlgdata.extdata.output.scalarExp
    simulatedLabelCtrlStatus.string = 'of constant';
else
    simulatedLabelCtrlStatus.string = 'of element';
end

if ~strcmp(tl_deblank(dlgdata.data.output.class, 2), 'default')
    % class is not default: disable tolerance controls
    toleranceEditCtrlStatus.enable = 'off';
    toleranceUnitLabelCtrlStatus.enable = 'off';

    % fill row with simulated values
    if ~isempty(constraint)
        lowerSimulatedValueCtrlStatus.string = sprintf('%0.6g', min(constraint));
        upperSimulatedValueCtrlStatus.string = sprintf('%0.6g', max(constraint));
    else
        lowerSimulatedValueCtrlStatus.string = 'n.a.';
        upperSimulatedValueCtrlStatus.string = 'n.a.';
    end
else
    lowerSimulatedValueCtrlStatus.string   = '';
    upperSimulatedValueCtrlStatus.string   = '';
    lowerCalculatedValueCtrlStatus.string  = '';
    upperCalculatedValueCtrlStatus.string  = '';
    lowerImplementedValueCtrlStatus.string = '';
    upperImplementedValueCtrlStatus.string = '';
end

% write control status of extra controls to the control
extraCtrlsList = {
    'toleranceEdit' ...
    'toleranceUnitLabel' ...
    'valEdit' ...
    'sampleTimeEdit' ...
    'useDDValueCheckbox'};
standardCtrlsList = {
    'simulatedLabel'...
    'upperSimulatedValue'...
    'lowerSimulatedValue'...
    'upperCalculatedValue'...
    'lowerCalculatedValue'...
    'upperImplementedValue'...
    'lowerImplementedValue'};
ctrlsList = [extraCtrlsList standardCtrlsList];
for ctrlsNo = 1:length(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end

% set standard controls
TLManageVariableCtrls('setCtrls', pageNum, dlgfig, dlgdata);
TLManageScalingCtrls('setCtrls', pageNum, dlgfig, dlgdata);

% set non-standard controls
TLSetCtrlsStatus(dlgfig, Children, extraCtrlsList);
